package and.bumper.close;


import java.util.ArrayList;
import java.util.List;

import and.bumper.close.bean.AppInfo;
import and.bumper.close.listener.ShakeEventListener;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ActivityManager;
import android.app.ActivityManager.MemoryInfo;
import android.app.ActivityManager.RunningAppProcessInfo;
import android.app.AlertDialog;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.hardware.Sensor;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.WindowManager;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
import android.widget.Toast;

@SuppressLint({ "ParserError" })
public class BumperCloseActivity extends Activity{
	
	 private SensorManager mSensorManager;
	 private ShakeEventListener mSensorListener;
	 private ArrayList<AppInfo> activeApps = null;
	 public static final int GONE = View.INVISIBLE;
	 TableLayout table;
	 int textSize = 0;
	 int checkSize = 0;
	 int imageSize = 0;
	 int displayWidthTotal = 0;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {    	
		super.onCreate(savedInstanceState);
		create();
	}
	
	public void create(){
		setContentView(R.layout.main);
		
		setElementRowSize();

		
		ActivityManager activityManager = (ActivityManager)BumperCloseActivity.this.getSystemService(ACTIVITY_SERVICE);
		
		long memory = getMemoryInfo(activityManager);
		
		this.setTitle("Available Memory: " + memory + "Mb");
		
		table = getTableActiveApps(table);
		
		//PARTE RELATIVA AL SENSORE DELL'ACCELLEROMETRO
        mSensorListener = new ShakeEventListener();
        mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
        mSensorManager.registerListener(mSensorListener,
            mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER),
            SensorManager.SENSOR_DELAY_UI);


        mSensorListener.setOnShakeListener(new ShakeEventListener.OnShakeListener() {
          public void onShake(){
        	  if (table!=null){
 				 ActivityManager am = (ActivityManager)getSystemService(ACTIVITY_SERVICE);

        		  for (int i=1; i<table.getChildCount(); i++){
        			 TableRow tableRow = (TableRow)table.getChildAt(i);
        			 
        			 CheckBox check =(CheckBox) tableRow.getChildAt(1);
        			 if(check.isChecked()){
        				 TextView textInfoApp = (TextView) tableRow.getChildAt(2);
        				 String packageName = textInfoApp.getText().toString();
        				 am.killBackgroundProcesses(packageName);
        			 }
        		  }
        	  }
        	  table.removeAllViewsInLayout();
      		  ActivityManager activityManager = (ActivityManager)BumperCloseActivity.this.getSystemService(ACTIVITY_SERVICE);
      		  
        	  long memory = getMemoryInfo(activityManager);
        	  BumperCloseActivity.this.setTitle("Available Memory: " + memory + "Mb");
      		  table = getTableActiveApps(table);
//	          Toast.makeText(BumperCloseActivity.this, "Le app selezionate sono state chiuse correttamente", Toast.LENGTH_SHORT).show();
          }
        });
        
	 }
	
	public void resume(){
		setElementRowSize();

		 table.removeAllViewsInLayout();
		 ActivityManager activityManager = (ActivityManager)BumperCloseActivity.this.getSystemService(ACTIVITY_SERVICE);
  		  
    	 long memory = getMemoryInfo(activityManager);
    	 BumperCloseActivity.this.setTitle("Available Memory: " + memory + "Mb");
  		 table = getTableActiveApps(table);
	}
	
	 @Override
	  protected void onResume() {
	    super.onResume();
//	    create();
	  }
	
	  @Override
	  protected void onStop() {
	    mSensorManager.unregisterListener(mSensorListener);
	    super.onStop();
	  }
	  
	  @SuppressLint("ParserError")
	  @Override
	  public boolean onKeyDown(int keyCode, KeyEvent event)
	  {
	      if ((keyCode == KeyEvent.KEYCODE_BACK))
	      {
	    	  getConfirmPopUp();
	      }
	      return super.onKeyDown(keyCode, event);
	  }  

	private ArrayList<AppInfo> getActiveApps() {

		ArrayList<AppInfo> res = new ArrayList<AppInfo>();
		ActivityManager activityManager = (ActivityManager)this.getSystemService(ACTIVITY_SERVICE);	

		List<RunningAppProcessInfo> procInfos = activityManager.getRunningAppProcesses();
		PackageManager pm = getPackageManager();		
		setNotification();
		for (int i=0; i<procInfos.size(); i++) {
			ApplicationInfo ai = null;
			try {
				ai = pm.getApplicationInfo(procInfos.get(i).processName, 0);
			} catch (final NameNotFoundException e) {
				e.printStackTrace();
			}
			if (ai!=null) {
				//Non Considera le app di Sistema
				if ((ai.flags & ApplicationInfo.FLAG_SYSTEM) == 1) {
					continue;
				}

				AppInfo app = new AppInfo();
				app.setApplicationName(ai.loadLabel(getPackageManager()).toString());
				app.setPackageName(ai.packageName);				
				app.setIcon(ai.loadIcon(getPackageManager()));
				app.setPid(procInfos.get(i).pid);
				
				res.add(app);
			}
		}

		return res;
	}
	
	private TableLayout getTableActiveApps(TableLayout tab){
		
		
		activeApps = getActiveApps();
		
				
//		Dialog dialog = new Dialog(tab.getContext());
//		dialog.setContentView(R.layout.table);
		
//		TableLayout table = (TableLayout) dialog.findViewById(R.id.tableGeneralShake);
		
		TableLayout table = tab;
		
		table = (TableLayout) this.findViewById(R.id.tableGeneralShake);
		
//		table = (TableLayout)LayoutInflater.from(this).inflate(R.layout.table, null);



//		dialog.show();
		
		
//		ListView app = (ListView) dialog.findViewById(R.id.players);
//		rosa.setAdapter(new RosaAdapter(dialog.getContext(), squadra
//				.getRosa()));
//		dialog.show();
		
				
		for (AppInfo appActive:activeApps) {
			TableRow row = new TableRow(this);
			LayoutInflater inflater = getLayoutInflater();
//			LayoutInflater mInflater = (LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
//			row = (TableRow) inflater.from(this).inflate(R.layout.row, null);
			row = (TableRow) inflater.inflate(R.layout.row, table, false);
			
			
			
//			row = (TableRow) table.findViewById(R.id.tableRowShake);
					
//			TableRow.LayoutParams rowLp = new TableRow.LayoutParams(
//			        ViewGroup.LayoutParams.WRAP_CONTENT,
//			        ViewGroup.LayoutParams.WRAP_CONTENT);
			
//			row.setLayoutParams(rowLp);
			
//			LinearLayout linearLayout = new LinearLayout(this);
//			LinearLayout.LayoutParams linearLp = new LinearLayout.LayoutParams(
//		            LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);		    
//			linearLayout.setLayoutParams(linearLp);
			
//			LinearLayout.LayoutParams linearLpImage = new LinearLayout.LayoutParams(48,48);		    
				    						
//			ImageView image = new ImageView(this);
			
			ImageView image = (ImageView)row.findViewById(R.id.imageShake);
			
			if (appActive.getIcon()!=null) {
				image.setImageDrawable(appActive.getIcon());
				image.setScaleType(ImageView.ScaleType.FIT_CENTER);
				image.setAdjustViewBounds(true);
			}
			
//			linearLayout.addView(image, linearLpImage);
			
//			LinearLayout.LayoutParams linearLpText = new LinearLayout.LayoutParams(
//		            LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);				
//			linearLpText.gravity = Gravity.CENTER;
//			linearLpText.leftMargin = 10;
			
//			TextView text = new TextView(this);
			
			TextView text = (TextView)row.findViewById(R.id.textShake);
			
			text.setTextAppearance(getApplicationContext(), android.R.style.TextAppearance_Medium);
			if (appActive.getApplicationName()!=null) {
				text.setText(appActive.getApplicationName());
			}			
			text.setWidth(textSize);
//			text.setPadding(0, 0, 0, 0);
//			linearLayout.addView(text, linearLpText);
			
//			CheckBox check = new CheckBox(this);
			CheckBox check = (CheckBox)row.findViewById(R.id.checkShake);
			check.setWidth(checkSize);
			check.setChecked(true);
			appActive.setSelect(true);
//			check.setPadding(0, 0, 0, 0);
//			row.addView(image);
//			row.addView(text);
//			row.findViewById(R.id.)
//			row.addView(linearLayout);
//			row.addView(check);
//			TextView textInfoApp = new TextView(this);
//			textInfoApp.setVisibility(View.GONE);
//			textInfoApp.setText(String.valueOf(appActive.getPackageName()));
//			row.addView(textInfoApp);
			table.addView(row);

		}
//		dialog.show();
		return table;
	}
	
	public void setNotification(){
		String ns = Context.NOTIFICATION_SERVICE;
        final int NOTIFICATION_ID = 1;

        NotificationManager mNotificationManager = (NotificationManager) getSystemService(ns);
        
        Intent notificationIntent = new Intent(getApplicationContext(), BumperCloseActivity.class);

        notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

        PendingIntent contentIntent = PendingIntent.getActivity(getApplicationContext(), 0, notificationIntent, 0);
        
        int icon = android.R.drawable.stat_notify_chat;
        CharSequence tickerText = "Bumper Close";
        long when = System.currentTimeMillis();
        
        Notification notification = new Notification(icon, tickerText, when);
        
        notification.setLatestEventInfo(getApplicationContext(), "Bumper Close", "Shake to close your app", contentIntent);
        
        mNotificationManager.notify(NOTIFICATION_ID, notification);

	}
	
	public void removeNotification(){
		String ns = Context.NOTIFICATION_SERVICE;

        NotificationManager mNotificationManager = (NotificationManager) getSystemService(ns);
        
        mNotificationManager.cancel(1);
	}
	
	public long getMemoryInfo(ActivityManager activityManager){
		//Prendo l'informazione relativa alla memoria disponibile e la stampo
		MemoryInfo mi = new MemoryInfo();
		activityManager.getMemoryInfo(mi);

		//Trasformo in MB 
		Long memory = mi.availMem / (1024*1024);
		return memory;
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu)
	{
		getMenuInflater().inflate(R.menu.menu, menu);
		return true;
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item)
	{
		switch (item.getItemId())
		{
			case R.id.menu_exit:{
				 getConfirmPopUp();
		         return false;
			}
			case R.id.menu_about:{
				Toast.makeText(this, R.string.about_clicked, 
					Toast.LENGTH_SHORT).show();
				return true;
			}
		}
		return super.onOptionsItemSelected(item);
	}
	
	public void getConfirmPopUp(){
		 new AlertDialog.Builder(this)
         .setIcon(android.R.drawable.ic_dialog_alert)
         .setTitle(R.string.quit)
         .setMessage(R.string.really_quit)
         .setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {
             public void onClick(DialogInterface dialog, int which) {
                 //Stop the activity
            	 BumperCloseActivity.this.removeNotification();
                 BumperCloseActivity.this.finish();    
             }
         })
         .setNegativeButton(R.string.no, null)
         .show();

//         return true;
	}
	
	public void setElementRowSize(){
		displayWidthTotal = ((WindowManager) this.getSystemService(Context.WINDOW_SERVICE))
				.getDefaultDisplay()
				.getWidth();
		textSize = Math.round((displayWidthTotal*60)/100);
		checkSize = Math.round((displayWidthTotal*20)/100);
		imageSize = Math.round((displayWidthTotal*20)/100);
	}
}